﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text;
using System.IO;

namespace LeadMaster.Helpers
{
  public static class PostData
  {
    
    public static List<string> PostRequest(string PostURL, List<string> ClientData)
    {
      List<string> responseFromServer = new List<string>();

      //ClientData.Add("f_1_email=&f_7_firstname=Sheila&f_9_lastname=Harrison&f_11_postcode=DE61FW&f_29_address1=26 Beresford Avenue&f_8_ipaddress=&f_51_source=&f_4_building=&f_2_mobile=&f_14_title=&f_28_phone1=01335348715&f_30_address2=Ashbourne Derbyshire&cid=24&sid=105");

      //string PostURL = "https://campaigns.databowl.com/api/v1/lead";

      try
      {
        foreach (var item in ClientData)
        {
          // Create a request using a URL that can receive a post. 
          WebRequest request = WebRequest.Create(PostURL);
          // Set the Method property of the request to POST.
          request.Method = "POST";
          // Create POST data and convert it to a byte array.
          // Set the ContentType property of the WebRequest.
          request.ContentType = "application/x-www-form-urlencoded";
          byte[] byteArray = Encoding.UTF8.GetBytes(item);
          // Set the ContentLength property of the WebRequest.
          request.ContentLength = byteArray.Length;
          // Get the request stream.
          Stream dataStream = request.GetRequestStream();
          // Write the data to the request stream.
          dataStream.Write(byteArray, 0, byteArray.Length);
          // Close the Stream object.
          dataStream.Close();
          // Get the response.
          WebResponse response = request.GetResponse();

          if (((HttpWebResponse)response).StatusDescription == "OK")
          {
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            responseFromServer.Add(reader.ReadToEnd() + " : " + item) ;

            // Clean up the streams.
            reader.Close();
            dataStream.Close();
          }

          response.Close();
        }

        return responseFromServer;
      }
      catch (Exception e)
      {
        responseFromServer.Add("Error : " + e.Message);
        return responseFromServer;
      }

    }

  }
}